package yxy.apple.database;

import java.io.File;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;

/**
 * session对象
 * 
 * @author hao.zhang
 * 
 */
public class HibernateUtil {
	private File file;
	private SessionFactory sessionFactory = null;

	public HibernateUtil(String filepath) throws Exception {
		file = new File(filepath);
		sessionFactory = getSessionFactory();
	}

	/**
	 * @return 获取会话工厂
	 */
	public SessionFactory getSessionFactory() throws Exception {
		// 生成一个注册机对象
		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure(file).build();
		// 使用注册机机对象serviceRegistry创建sessionFactory
		sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
		return sessionFactory;
	}

	/**
	 * @return 获取会话对象
	 */
	public Session getSession() {
		return sessionFactory.openSession();
	}
}
